package com.ruoyi.system.controller;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ToolUtil;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.oss.minio.MinIoService;
import io.minio.errors.*;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.system.domain.JacFileInfo;
import com.ruoyi.system.service.IJacFileInfoService;
import org.springframework.web.multipart.MultipartFile;
import org.xmlpull.v1.XmlPullParserException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 文件信息 提供者
 *
 * @author wjy
 * @date 2020-06-19
 */
@RestController
@RequestMapping("file")
public class JacFileInfoController extends BaseController
{

	@Autowired
	private IJacFileInfoService jacFileInfoService;

	@Autowired
	private MinIoService minIoService;

	private static final Logger log = LoggerFactory.getLogger(JacFileInfoController.class);

	/**
	 * 根据id获取文件信息
	 */
	@GetMapping("get/{fileid}")
	public JacFileInfo get(@PathVariable("fileid") Long fileid)
	{
		return jacFileInfoService.selectJacFileInfoById(fileid);

	}

	/**
	 * 查询文件信息列表
	 */
	@GetMapping("list")
	public R list(JacFileInfo jacFileInfo)
	{
		startPage();
        return result(jacFileInfoService.selectJacFileInfoList(jacFileInfo));
	}


	/**
	 * 新增保存文件信息
	 */
	@PostMapping("save")
	@ApiOperation(value = "文件上传 ~", notes = "欢迎")
	public R addSave(MultipartFile file) throws InvalidPortException, InvalidEndpointException, IOException, XmlPullParserException, NoSuchAlgorithmException, RegionConflictException, InvalidKeyException, ErrorResponseException, NoResponseException, InvalidBucketNameException, InsufficientDataException, InternalException {
		minIoService.setMinioClient();
		String s = minIoService.minioUpload(file); //返回的是bucketname/encodename 的形式
		int i = s.indexOf("/");
		JacFileInfo jacFileInfo = new JacFileInfo();
		jacFileInfo.setBucketname(s.substring(0,i));
		jacFileInfo.setEncodename(s.substring(i+1));
		jacFileInfo.setRealname(file.getOriginalFilename());
		return toAjax(jacFileInfoService.insertJacFileInfo(jacFileInfo));
	}

	/**
	 * 修改保存文件信息
	 */
	@PostMapping("update")
	public R editSave(@RequestBody JacFileInfo jacFileInfo)
	{

		return toAjax(jacFileInfoService.updateJacFileInfo(jacFileInfo));
	}

	/**
	 * 删除${tableComment}
	 */
	@PostMapping("remove")
	public R remove(String ids)
	{
		return toAjax(jacFileInfoService.deleteJacFileInfoByIds(ids));
	}

	@ApiOperation(value = "miniosssss下载 ~", notes = "欢迎")
	@GetMapping("common/download")
	public void fileDownload(String bucketName, String fileName, HttpServletResponse response, HttpServletRequest request)
	{
		try
		{
			if (!FileUtils.isValidFilename(fileName))
			{
				throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
			}
//            String realFileName = DateUtils.dateTimeNow() + fileName.substring(fileName.indexOf("_") + 1);
			String realFileName = fileName;
			String filePath = ToolUtil.getDownloadPath() + fileName;
			response.setCharacterEncoding("utf-8");
			// 下载使用"application/octet-stream"更标准
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + FileUtils.setFileDownloadHeader(request, realFileName));
			minIoService.setMinioClient();
			minIoService.minioDownload(bucketName,fileName,response.getOutputStream());

		}
		catch (Exception e)
		{
			log.error("下载文件失败", e);
		}
	}

	@ApiOperation(value = "minio上传 ~", notes = "欢迎")
	@PostMapping("common/upload")
	public String upload(MultipartFile file) throws IOException, XmlPullParserException, NoSuchAlgorithmException, RegionConflictException, InvalidKeyException, ErrorResponseException, NoResponseException, InvalidBucketNameException, InsufficientDataException, InternalException, InvalidPortException, InvalidEndpointException {
		minIoService.setMinioClient();
		return minIoService.minioUpload(file);
	}

}
